package com.illtamer.infinite.sillage.config.exception;

import com.illtamer.infinite.sillage.exception.SillageException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.TreeMap;

/**
 * Controller 统一异常处理
 * */
@Slf4j
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    @ExceptionHandler({Exception.class})
    public ModelAndView exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        if (!"/error".equals(request.getRequestURI()))
            log.error("Error occurred when {}: {}", request.getMethod(), request.getRequestURI(), e);
        else
            log.debug("Error occurred when {}: {}", request.getMethod(), request.getRequestURI(), e);
        Map<String, Object> args = new TreeMap<>();
            args.put("code", response.getStatus());
            args.put("reason", e.getMessage());
        return new ModelAndView("error", args);
    }

}
